import MsgUtils from "@/common/utils/MsgUtils";
import {FormInstance} from "element-plus/es";

export class FormValidate {

    private successFunc = () => {
        //成功的回调
    };
    //失败的回调,默认未知错误
    private errorFunc = (valid: boolean, fields: any) => {
        //失败的回调
        MsgUtils.errorMsg('数据校验错误,请检查!')
    };

    public errorMsg(msg: string) {
        this.errorFunc = (valid, fields) => {
            MsgUtils.errorMsg(msg)
        };
        return this;
    }

    public success(successFunc: () => any) {
        this.successFunc = successFunc;
        return this;
    }

    public error(errorFunc: (valid: boolean, fields: any) => any) {
        this.errorFunc = errorFunc;
        return this;
    }

    public async validate(ref: FormInstance) {

        await ref.validate((valid, fields) => {
            if (valid) {
                this.successFunc();
            } else {
                this.errorFunc(valid, fields);
            }
        });
    }
}
